package com.ncmmall.mall.controller.business.news;

import com.ncmmall.application.business.news.NewsApplication;
import com.ncmmall.application.securitys.logs.OperationLogApplication;
import com.feijin.commons.webs.Webs;
import com.ncmmall.domain.business.news.News;
import com.ncmmall.domain.business.news.QNews;
import com.ncmmall.mall.controller.securitys.shiro.Securitys;
import com.ncmmall.mall.params.PageParams;
import com.ncmmall.querychannel.QueryPage;
import com.ncmmall.querychannel.QueryPageRequest;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.collect.ImmutableMap;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 公告管理
 *
 * @author likaikai
 * @date 2019-07-11 15:57
 */
@Controller
@RequestMapping("/mall/news")
public class NewsController {

    private Logger logger = LoggerFactory.getLogger(NewsController.class);

    @Autowired
    private QueryChannelService queryChannelService;

    @Autowired
    private NewsApplication newsApplication;

    @Autowired
    private OperationLogApplication logApplication;

    /**
     * 公告列表
     *
     * @param model
     * @param pageParams
     * @param param
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(Model model, PageParams pageParams, News params) {

        QueryPageRequest pageRequest = new QueryPageRequest().setPageNo(pageParams.getPageNo()).setPageSize(pageParams.getPageSize());

        Map<String, Object> map = new HashMap<>(2);
        String sql = buildSql("select * from mall_news where 1 = 1", map, params);

        QueryPage<News> page = queryChannelService.queryPageEntity(sql, pageRequest.setParams(map), News.class);

        model.addAttribute("page", page);
        model.addAttribute("params", params);

        return "mall/news/list";
    }

    /**
     * 条件查询
     *
     * @param sql
     * @param map
     * @param params
     * @return
     */
    private String buildSql(String sql, Map<String, Object> map, News params) {

        sql += " and platformType = :type ";
        map.put("type", params.getPlatformType());

        if (StringUtils.isNotBlank(params.getTitle())) {
            sql += " and title like :title";
            map.put("title", "%" + params.getTitle() + "%");
        }

        if (params.getStatus() > 0) {
            sql += " and status = :status";
            map.put("status", params.getStatus());
        }

        if (params.getRecommend() > 0) {
            sql += " and recommend = :recommend";
            map.put("recommend", params.getRecommend());
        }

        sql += " order by createTime desc";

        return sql;
    }


    /**
     * 创建公告
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public String create(Model model) {
        model.addAttribute("_method", "POST");
        model.addAttribute("news", new News());
        return "mall/news/form";
    }


    /**
     * 创建公告
     *
     * @param requestWith
     * @param news
     * @return
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> create(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, News news) {
        try {
            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalArgumentException("request must be ajax");
            }

            newsApplication.create(news);
            logApplication.eventOfSystem(Securitys.currentUser(), "添加公告", Securitys.getIp(request));
            return ImmutableMap.of("status", true, "message", "创建成功");

        } catch (IllegalArgumentException e) {

            return ImmutableMap.of("status", false, "message", e.getMessage());

        } catch (Exception e) {

            logger.error("公告创建异常", e);
            return ImmutableMap.of("status", false, "message", "创建异常");

        }
    }


    /**
     * 编辑公告
     *
     * @param model
     * @param id
     * @return
     */
    @RequestMapping(value = "/modify", method = RequestMethod.GET)
    public String create(Model model, long id) {
        News news = queryChannelService.findOne(QNews.news.id.eq(id), News.class);
        model.addAttribute("news", news);
        model.addAttribute("_method", "PUT");
        return "mall/news/form";
    }


    /**
     * 编辑公告
     *
     * @param requestWith
     * @param news
     * @return
     */
    @RequestMapping(value = "/modify", method = RequestMethod.PUT)
    @ResponseBody
    public Map<String, Object> modify(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, News news) {
        try {
            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalArgumentException("request must be ajax");
            }

            newsApplication.modify(news);
            logApplication.eventOfSystem(Securitys.currentUser(), "编辑公告", Securitys.getIp(request));
            return ImmutableMap.of("status", true, "message", "编辑成功");

        } catch (IllegalArgumentException e) {

            return ImmutableMap.of("status", false, "message", e.getMessage());

        } catch (Exception e) {

            logger.error("公告编辑异常", e);
            return ImmutableMap.of("status", false, "message", "编辑异常");

        }
    }

    /**
     * 下架公告
     *
     * @param requestWith
     * @param news
     * @return
     */
    @RequestMapping(value = "/disable", method = RequestMethod.PUT)
    @ResponseBody
    public Map<String, Object> disable(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, News news) {
        try {
            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalArgumentException("request must be ajax");
            }

            newsApplication.disable(news.getId());
            logApplication.eventOfSystem(Securitys.currentUser(), "下架公告", Securitys.getIp(request));
            return ImmutableMap.of("status", true, "message", "下架成功");

        } catch (Exception e) {

            logger.error("公告下架异常", e);
            return ImmutableMap.of("status", false, "message", "下架异常");

        }
    }

    /**
     * 批量下架公告
     *
     * @param requestWith
     * @param news
     * @return
     */
    @RequestMapping(value = "/disables", method = RequestMethod.PUT)
    @ResponseBody
    public Map<String, Object> disables(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, String data) {
        try {
            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalArgumentException("request must be ajax");
            }

            newsApplication.disables(data);
            logApplication.eventOfSystem(Securitys.currentUser(), "批量下架公告", Securitys.getIp(request));
            return ImmutableMap.of("status", true, "message", "下架成功");

        } catch (Exception e) {

            logger.error("公告批量下架异常", e);
            return ImmutableMap.of("status", false, "message", "下架异常");

        }
    }


    /**
     * 上架公告
     *
     * @param requestWith
     * @param news
     * @return
     */
    @RequestMapping(value = "/enable", method = RequestMethod.PUT)
    @ResponseBody
    public Map<String, Object> enable(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, News news) {
        try {
            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalArgumentException("request must be ajax");
            }

            newsApplication.enabled(news.getId());
            logApplication.eventOfSystem(Securitys.currentUser(), "上架公告", Securitys.getIp(request));
            return ImmutableMap.of("status", true, "message", "上架成功");

        } catch (Exception e) {

            logger.error("公告上架异常", e);
            return ImmutableMap.of("status", false, "message", "上架异常");

        }
    }


    /**
     * 批量上架公告
     *
     * @param requestWith
     * @param news
     * @return
     */
    @RequestMapping(value = "/enables", method = RequestMethod.PUT)
    @ResponseBody
    public Map<String, Object> enables(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, String data) {
        try {
            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalArgumentException("request must be ajax");
            }

            newsApplication.enables(data);
            logApplication.eventOfSystem(Securitys.currentUser(), "批量上架公告", Securitys.getIp(request));
            return ImmutableMap.of("status", true, "message", "上架成功");

        } catch (Exception e) {

            logger.error("公告批量上架异常", e);
            return ImmutableMap.of("status", false, "message", "上架异常");

        }
    }

    /**
     * 删除公告
     *
     * @param requestWith
     * @param news
     * @return
     */
    @RequestMapping(value = "/remove", method = RequestMethod.DELETE)
    @ResponseBody
    public Map<String, Object> remove(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, News news) {
        try {
            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalArgumentException("request must be ajax");
            }

            newsApplication.remove(news.getId());
            logApplication.eventOfSystem(Securitys.currentUser(), "删除上架公告", Securitys.getIp(request));
            return ImmutableMap.of("status", true, "message", "删除成功");

        } catch (Exception e) {

            logger.error("公告删除异常", e);
            return ImmutableMap.of("status", false, "message", "删除异常");

        }
    }


    /**
     * 推荐公告
     *
     * @param requestWith
     * @param news
     * @return
     */
    @RequestMapping(value = "/recommend", method = RequestMethod.PUT)
    @ResponseBody
    public Map<String, Object> recommend(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, long id) {
        try {
            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalArgumentException("request must be ajax");
            }

            newsApplication.recomend(id);
            logApplication.eventOfSystem(Securitys.currentUser(), "推荐公告", Securitys.getIp(request));
            return ImmutableMap.of("status", true, "message", "推荐成功");

        } catch (Exception e) {

            logger.error("公告推荐异常", e);
            return ImmutableMap.of("status", false, "message", "推荐异常");

        }
    }


    /**
     * 取消推荐公告
     *
     * @param requestWith
     * @param news
     * @return
     */
    @RequestMapping(value = "/notRecommend", method = RequestMethod.PUT)
    @ResponseBody
    public Map<String, Object> notRecomend(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, long id) {
        try {
            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalArgumentException("request must be ajax");
            }

            newsApplication.notRecomend(id);
            logApplication.eventOfSystem(Securitys.currentUser(), "取消推荐公告", Securitys.getIp(request));
            return ImmutableMap.of("status", true, "message", "取消推荐成功");

        } catch (Exception e) {

            logger.error("公告取消推荐异常", e);
            return ImmutableMap.of("status", false, "message", "取消推荐异常");

        }
    }

}
